package com.wsjc.sso.client;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 93733
 * 登入过滤器
 */
public class AuthenticationFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);

    private String casLoginUrl = null;
    private String backUrl = null;
    private String verifyUrl = null;
    private String logoutUrl = null;
    
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    	this.casLoginUrl = filterConfig.getInitParameter("casLoginUrl");
    	this.backUrl = filterConfig.getInitParameter("backUrl");
    	this.verifyUrl = filterConfig.getInitParameter("verifyUrl");
    	this.logoutUrl = filterConfig.getInitParameter("logoutUrl");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 效验配置
        if(null == casLoginUrl || "".equals(casLoginUrl)){
    		logger.info("Filter init-param 'casLoginUrl' set is error...please check web.xml filter setting!");
    		return ;
    	}
        if(null == backUrl || "".equals(backUrl)){
        	logger.info("Filter init-param 'backUrl' set is error...please check web.xml filter setting!");
        	return ;
        }
        if(null == verifyUrl || "".equals(verifyUrl)){
        	logger.info("Filter init-param 'verifyUrl' set is error...please check web.xml filter setting!");
        	return ;
        }
        if(null == logoutUrl || "".equals(logoutUrl)){
        	logger.info("Filter init-param 'logoutUrl' set is error...please check web.xml filter setting!");
        	return ;
        }
        
        // 没有登录
        if (null == request.getSession().getAttribute("TOKEN") || "".equals(request.getSession().getAttribute("TOKEN"))) {
        	
        	String url = casLoginUrl + "?url=" + backUrl;
        	
            try {
            	// 效验token
            	String token = request.getParameter("token");
            	if (null == token || "".equals(token)) {
            		//token 无效 则跳转至认证中心信息认证
            		response.sendRedirect(url);
            		return;
                }
                // 判断st是否有效  有效则直接放通 如果st无效 则去认证中心认证
            	ApiCommonResultVo apiCommonResultVo = validateToken(token, request.getSession().getId());

                // token 有效 则直接登录成功
                if ("0".equals(apiCommonResultVo.getCode()) && "SUCCESS".equals(apiCommonResultVo.getMsg())) {
                	WjUser wjUser = (WjUser) apiCommonResultVo.getData();
                    request.getSession().setAttribute("USER", wjUser);
                    filterChain.doFilter(request, response);
                    return;
                } else {
                    //token 无效 则跳转至认证中心信息认证
//                    	String url = "http://localhost:8080/sso-server/tologin" + "?url=" + http://localhost:8999/sso-client1/index";
                    response.sendRedirect(url);
                }
            } catch (Exception e) {
                logger.error("doFilter error...", e);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 校验service token是否有效
     *
     * @param token 认证中心分发的token
     * @return 返回校验结果
     */
    private ApiCommonResultVo validateToken(String token, String sessionId) {

        try {
        	String strUrl = verifyUrl +"?token=" + token + "&sessionId=" + sessionId + "&logoutUrl=" + logoutUrl;
//        	String strUrl = "http://localhost:8080/sso-server/verifyst?token=" + token + "&sessionId=" + sessionId + "&logoutUrl=" + "http://localhost:8999/sso-client1/logout";
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            ApiCommonResultVo apiCommonResultVo = JSON.parseObject(sb.toString(), ApiCommonResultVo.class);
            return apiCommonResultVo;
        } catch (Exception e) {
        	logger.error("validate token fail..", e);
        	return null;
        }

    }

    @Override
    public void destroy() {

    }
}
